<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>商城后台</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/lib/layui-v2.5.5/css/layui.css}" media="all">
    <link rel="stylesheet" th:href="@{/css/public.css}" media="all">
    <link rel="stylesheet" th:href="@{/lib/layui_ext/dtree/dtree.css}" >
    <link rel="stylesheet" th:href="@{/lib/layui_ext/dtree/font/dtreefont.css}" >
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>
<body>

<span th:replace="common_page::common"></span>

<div class="layui-form layuimini-form">
    <div class="layui-form-item">
        <label class="layui-form-label required">商标注册地区</label>
        <div class="layui-input-block" >
            <select name="trademarkAreaType"  lay-search="">
                <option value="1" >中国大陆地区</option>
                <option value="2">香港、澳门特别行政区，台湾省和境外国家</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">品牌名(中文)</label>
        <div class="layui-input-block">
            <input type="text" name="chineseName" lay-verify="required" maxlength="255" lay-reqtext="不能为空" placeholder="请输入品牌名(中文)" value="" class="layui-input">
            <tip>填写品牌名(中文)。</tip>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label ">品牌名(英文)</label>
        <div class="layui-input-block">
            <input type="text" name="englishName"  maxlength="255" lay-reqtext="不能为空" placeholder="请输入品牌名(英文)" value="" class="layui-input">
            <tip>填写品牌名(英文)。</tip>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">LOGO</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="uploadLogoPath">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
        </div>
        <input type="hidden" id="logoPath" name="logoPath"  >
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">LOGO预览</label>
        <div class="layui-input-block">
            <img  id="previewLogoPath" th:width="240" th:height="220">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label ">商标注册号</label>
        <div class="layui-input-block">
            <input type="text" name="registNumber1"  maxlength="200" lay-reqtext="不能为空" placeholder="请输入商标注册号" value="" class="layui-input">
            <tip>填写商标注册号。</tip>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label ">商标注册号</label>
        <div class="layui-input-block">
            <input type="text" name="registNumber2"  maxlength="200" lay-reqtext="不能为空" placeholder="请输入商标注册号" value="" class="layui-input">
            <tip>填写商标注册号。</tip>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label ">发源地</label>
        <div class="layui-input-block">
            <input type="text" name="seminary"  maxlength="200" lay-reqtext="不能为空" placeholder="请输入发源地" value="" class="layui-input">
            <tip>填写发源地。</tip>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label ">品牌所有人</label>
        <div class="layui-input-block">
            <input type="text" name="ownerName"  maxlength="100" lay-reqtext="不能为空" placeholder="请输入所有人" value="" class="layui-input">
            <tip>填写所有人。</tip>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">所属分类</label>
        <div class="layui-input-block">
            <input type="hidden" name="categoryIdCache" id="categoryIdCache"  >
            <input type="text" readonly  id="selectcategoryIdCache" lay-verify="required"  placeholder="请选择所属分类"  class="layui-input" >
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block" >
            <select name="enabledStatus"  lay-search="">
                <option value="1" >有效</option>
                <option value="0">无效</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
        </div>
    </div>
</div>
<script th:src="@{/lib/layui-v2.5.5/layui.js}" charset="utf-8"></script>
<script>
    layui.config({
        base: basePath+'/lib/layui_ext/dtree/' //配置 layui 第三方扩展组件存放的基础目录
    }).extend({
        dtree: 'dtree' //定义该组件模块名
    }).use(['form','tree','dtree','upload','laydate'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.$;

        var tree = layui.tree;
        var dtree = layui.dtree;
        var upload = layui.upload;

        //执行实例
        var uploadInst = upload.render({
            elem: '#uploadLogoPath' //绑定元素
            ,url: '/product/brand/upload/logo' //上传接口
            ,data:{brandId:-1}
            ,done: function(res){
                if(res.code==1)
                {
                    layer.msg(res.msg);
                }
                $("#previewLogoPath").attr("src",res.data.httpLogoPath);
                $("#logoPath").val(res.data.logoPath);
            }
            ,error: function(){
                layer.msg("上传LOGO异常");
            }
        });

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            if(data.field.chineseName==""&&data.field.englishName=="")
            {
                layer.msg("品牌名不能为空");
                return false;
            }
            $.ajax({
                url:"[[@{/product/brand/save}]]",
                contentType: "application/json; charset=utf-8",
                type:'POST',
                data:JSON.stringify(data.field),
                success:function(data){
                    if(data.code<=0) {
                        layer.msg(data.msg);
                        return false;
                    }
                    var index = layer.alert(data.msg, {
                        title: '提示信息'
                    }, function () {
                        // 关闭弹出层
                        layer.close(index);
                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.location.reload();
                        parent.layer.close(iframeIndex);

                    });
                }
            });
            return false;
        });


        /**
         * 拿到所有选中节点的ID
         * @param data
         * @param idArray
         */
        function getCheckdNodeId(data,idArray)
        {
            for(var i=0;i<data.length;i++)
            {
                categoryTreeDataArray.push(data[i]);
                if(data[i].state.checked==true)
                {
                    idArray.push(parseInt(data[i].id));
                }
                if(data[i].children!=null&&data[i].children.length>0)
                {
                    getCheckdNodeId(data[i].children,idArray);
                }
            }
        }


        /**
         * 拿到指定节点对象
         */
        function getNodeObject(id)
        {
            if(id!=-1) {
                for (var i = 0; i < categoryTreeDataArray.length; i++) {
                    if (categoryTreeDataArray[i].id == id) {
                        return categoryTreeDataArray[i];
                    }
                }
            }
            return null;
        }


        /**
         * 拿到上级节点信息
         */
        function getParentNode(categoryArray,pid)
        {
            if(pid!=-1) {
                for (var i = 0; i < categoryTreeDataArray.length; i++) {

                    if (categoryTreeDataArray[i].id == pid) {
                        var exists = false;
                        //判断上级节点ID是否已经保存了
                        for (var j = 0; j < categoryArray.length; j++) {
                            if (categoryArray[j].id == pid) {
                                exists = true;
                            }
                        }
                        //避免上级节点ID重复保存两份
                        if (!exists) {
                            if(categoryTreeDataArray[i].pid!=-1) {
                                categoryArray.push({
                                    nodeId: categoryTreeDataArray[i].nodeId,
                                    name: categoryTreeDataArray[i].name,
                                    id: categoryTreeDataArray[i].id,
                                    pid: categoryTreeDataArray[i].pid
                                });
                            }
                        }

                        if (categoryTreeDataArray[i].pid != -1) {
                            //找到这个节点的上级节点
                            getParentNode(categoryArray, categoryTreeDataArray[i].pid);
                        }
                    }
                }
            }
        }

        function setCategoryNamePath(pid,selectNodeObject,categoryArray)
        {
            for (var i = 0; i < categoryArray.length; i++) {
                if (pid == categoryArray[i].id) {
                    selectNodeObject.name = categoryArray[i].name + "》" + selectNodeObject.name;
                    if (categoryArray[i].pid != -1) {
                        setCategoryNamePath(categoryArray[i].pid, selectNodeObject, categoryArray);
                    }
                }
            }
        }

        $("#selectcategoryIdCache").click(function(){

            var idValue = $("#id").val();
            index = layer.open({
                title: '选择类别',
                type: 1,
                shade: 0.2,
                maxmin:true,
                area: ['40%', '70%'],
                btn: ['确定'],
                content: "<ul id='categoryTree' class='dtree' data-id='0' ></ul>",
                success:function(layero){
                    loadding = layer.load();
                    $.ajax({
                        url:"[[@{/}]]product/brand/query/category/tree",
                        type:'POST',
                        data:{brandId:idValue},
                        success:function(data){
                            if(data.code==1)
                            {
                                //已选择节点
                                var idArray = new Array();
                                categoryTreeDataArray = new Array();
                                getCheckdNodeId(data.data,idArray);
                                categoryTree = dtree.render({
                                    elem: "#categoryTree",//html中的id值
                                    data:data.data,
                                    width:'100%',
                                    checkbarType: "no-all",
                                    checkbar: true,  //开启复选框
                                    checkbarData: "choose",// 记录选中（默认）， "change"：记录变更， "all"：记录全部， "halfChoose"："记录选中和半选（V2.5.0新增）"
                                    done: function (res, $ul, first) {
                                        if (first) {
                                            if(idArray!=null&&idArray.length>0) {
                                                dtree.chooseDataInit("categoryTree",  idArray.join(",")); //"001001,001002"被选中的子节点id
                                                dtree.initNoAllCheck("categoryTree");// 反选半选状态(原始数据中父节点的选中或半选状态并没有被带上)
                                            }
                                        }

                                    }
                                });
                            }
                        },
                        complete:function()
                        {
                            layer.close(loadding);
                        }
                    });

                },
                yes: function(index, layero){
                    var selectNodes = categoryTree.getCheckbarNodesParam("categoryTree");
                    if(selectNodes==null||selectNodes.length<=0)
                    {
                        layer.msg("请选择类别");
                        return false;
                    }
                    var categoryArray =  new Array();
                    for (var i = 0; i < selectNodes.length; i++) {
                        var selectNodeObject = getNodeObject(selectNodes[i].nodeId);
                        console.log(selectNodeObject);
                        if(selectNodeObject.pid!=-1) {
                            selectNodeObject = {
                                nodeId: selectNodeObject.nodeId,
                                name: selectNodeObject.name,
                                pid: selectNodeObject.pid,
                                id: selectNodeObject.id
                            };
                            categoryArray.push(selectNodeObject);
                            getParentNode(categoryArray, selectNodeObject.pid, selectNodeObject);
                        }
                    }

                    for(var p=0;p<categoryArray.length;p++)
                    {
                        setCategoryNamePath(categoryArray[p].pid, categoryArray[p], categoryArray);
                    }

                    var categoryIdCache="";
                    var categoryNames="";
                    for (var j = 0; j < categoryArray.length; j++) {
                        categoryIdCache+=categoryArray[j].nodeId;
                        categoryNames+=categoryArray[j].name;
                        if(j+1<categoryArray.length)
                        {
                            categoryIdCache+=",";
                            categoryNames+="、";
                        }
                    }

                    $("#categoryIdCache").val(categoryIdCache);
                    $("#selectcategoryIdCache").val(categoryNames);

                    layer.close(index);
                }
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        });


    });
</script>
</body>
</html>